/*
****************************************************************************************************************************
*/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('MarketEntityCheck') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
	PRINT 'Droping procedure dbo.MarketEntityCheck'
	DROP PROCEDURE dbo.MarketEntityCheck
END
GO

PRINT 'Creating procedure dbo.MarketEntityCheck'
GO

CREATE PROCEDURE dbo.MarketEntityCheck
AS
BEGIN
	-- Start code added temporarily for LINQ (Auto-generated Type) 
	SET FMTONLY OFF;
	-- End code added temporarily

	IF OBJECT_ID('tempdb..#CalcBidOffer') IS NOT NULL
	BEGIN
		DROP TABLE #CalcBidOffer
	END

	SELECT 
		Ent.MarketEntityId, 
		ROW_NUMBER() OVER (PARTITION BY Ent.MarketEntityId 
		ORDER BY OrderPrice DESC, OrderDate) AS RowNumber,
		Ord.OrderPrice,
		Ord.OrderId
	INTO #CalcBidOffer
	FROM dbo.[Order] Ord
	JOIN dbo.MarketEntity Ent ON Ord.MarketEntityId = Ent.MarketEntityId
	WHERE Ord.Operation = 0 -- Bid
	AND Ord.[Status] = 0 -- Active
	ORDER BY OrderPrice DESC, OrderDate

	IF OBJECT_ID('tempdb..#CalcAskOffer') IS NOT NULL
	BEGIN
		DROP TABLE #CalcAskOffer
	END

	SELECT 
		Ent.MarketEntityId, 
		ROW_NUMBER() OVER (PARTITION BY Ent.MarketEntityId 
		ORDER BY OrderPrice ASC, OrderDate) AS RowNumber,
		Ord.OrderPrice,
		Ord.OrderId
	INTO #CalcAskOffer
	FROM dbo.[Order] Ord
	JOIN dbo.MarketEntity Ent ON Ord.MarketEntityId = Ent.MarketEntityId
	WHERE Ord.Operation = 1 -- ASK 
	AND Ord.[Status] = 0 -- Active
	ORDER BY OrderPrice ASC, OrderDate

	DELETE FROM #CalcBidOffer WHERE RowNumber > 1
	DELETE FROM #CalcAskOffer WHERE RowNumber > 1

	IF OBJECT_ID('tempdb..#TradeConfirm') IS NOT NULL
	BEGIN
		DROP TABLE #TradeConfirm
	END	

	SELECT DISTINCT UserInfoId, UnbalansedPrice AS UnbalansedPrice
	FROM 
	(
		SELECT 
			BidOrder.TraderId AS UserInfoId, 0 AS UnbalansedPrice
		FROM dbo.MarketEntity Main
		JOIN #CalcBidOffer AS Bid ON Main.MarketEntityId = Bid.MarketEntityId
		JOIN dbo.[Order] BidOrder ON Bid.OrderId = BidOrder.OrderId
		JOIN #CalcAskOffer AS Ask ON Main.MarketEntityId = Ask.MarketEntityId
		WHERE Ask.OrderId IS NOT NULL AND Bid.OrderId IS NOT NULL AND Bid.OrderPrice = Ask.OrderPrice
		UNION ALL
		SELECT 
			AskOrder.TraderId AS UserInfoId, 0 AS UnbalansedPrice
		FROM dbo.MarketEntity Main
		JOIN #CalcBidOffer AS Bid ON Main.MarketEntityId = Bid.MarketEntityId
		JOIN #CalcAskOffer AS Ask ON Main.MarketEntityId = Ask.MarketEntityId
		JOIN dbo.[Order] AskOrder ON Ask.OrderId = AskOrder.OrderId
		WHERE Ask.OrderId IS NOT NULL AND Bid.OrderId IS 
		NOT NULL AND Bid.OrderPrice = Ask.OrderPrice
	) MatchPaire

END
GO